package com.franklin.ideaplugin.maphelper.col.declaration.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.franklin.ideaplugin.api.beans.declaration.impl.FieldDeclaration;
import com.franklin.ideaplugin.api.utils.psi.PsiClassUtils;
import com.franklin.ideaplugin.maphelper.beans.colmember.IColMember;
import com.franklin.ideaplugin.maphelper.col.declaration.IColDeclaration;
import com.franklin.ideaplugin.maphelper.utils.PsiCollectionUtils;
import com.franklin.ideaplugin.maphelper.utils.PsiMapUtils;
import com.google.common.collect.Sets;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * @author Ye Junhui
 * @since 2024/3/6
 */
public class FieldColDeclaration implements IColDeclaration<FieldDeclaration> {

    private FieldDeclaration fieldDeclaration;

    public FieldColDeclaration(FieldDeclaration fieldDeclaration) {
        this.fieldDeclaration = fieldDeclaration;
    }

    @Override
    public FieldDeclaration getDeclaration() {
        return fieldDeclaration;
    }

    @Override
    public Collection<IColMember> getColMembers() {
        PsiElement psiElement = fieldDeclaration.getVariable().getPsiElement();
        PsiClass psiClass = PsiTreeUtil.getParentOfType(psiElement, PsiClass.class);

        //类型
        PsiType psiType = fieldDeclaration.getVariable().getPsiType();
        PsiClassType psiClassType = (PsiClassType) psiType;
        PsiClass typeClass = psiClassType.resolve();

        //结果
        Set<IColMember> result = Sets.newLinkedHashSet();

        //代码块
        List<PsiClassInitializer> psiClassInitializerList = PsiTreeUtil.getChildrenOfTypeAsList(psiClass, PsiClassInitializer.class);
        for (PsiClassInitializer psiClassInitializer : psiClassInitializerList) {
            PsiCodeBlock psiCodeBlock = PsiTreeUtil.getChildOfType(psiClassInitializer, PsiCodeBlock.class);
            List<IColMember> psiColMemberInCodeBlock = Collections.emptyList();
            if (PsiClassUtils.isJavaMapClass(typeClass)){
                psiColMemberInCodeBlock = PsiMapUtils.findMapMemberInCodeBlock(fieldDeclaration.getVariable(), psiCodeBlock);
            }else if (PsiClassUtils.isJavaCollectionClass(typeClass)){
                psiColMemberInCodeBlock = PsiCollectionUtils.findCollectionMemberInCodeBlock(fieldDeclaration.getVariable(),psiCodeBlock);
            }
            CollectionUtil.addAll(result, psiColMemberInCodeBlock);
        }

        return result;
    }
}
